package com.pony.iphone.service.impl;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.pony.iphone.properties.SshConfigProperties;
import com.pony.iphone.service.ErrorService;
import com.pony.iphone.service.SshService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;

@Service
public class SshServiceImpl implements SshService {

    private static final String HOST = "api.jb.51wmsy.com";
    private static final String USERNAME = "ubuntu";
    private static final String PASSWORD = "209209cN*()209";
    private static final int PORT = 7721;  // 修改为7721端口

    @Autowired
    private SshConfigProperties sshConfig;

    /**
     * 测试SSH连接
     */
    @Override
    public boolean testConnection() {
        Session session = null;
        try {
            JSch jsch = new JSch();
            // 使用7721端口
            session = jsch.getSession(sshConfig.getUsername(), sshConfig.getHost(), sshConfig.getPort());
            session.setPassword(sshConfig.getPassword());
            
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            // 10秒超时
            session.connect(10000);
            return true;
            
        } catch (Exception e) {
            System.err.println("SSH连接测试失败: " + e.getMessage());
            return false;
        } finally {
            if (session != null) session.disconnect();
        }
    }

    /**
     * 通过 IP 查询系统日志
     * @param ip 手机ip
     * @return
     * @throws Exception
     */
    @Override
    public String searchSyslogByIp(String ip) throws Exception {
        // 清理IP地址
        String cleanedIp = ip.replaceAll("\\s+", "");
        System.out.println("Service层 - 清理后IP: '" + cleanedIp + "'");

        // 先测试连接
        if (!testConnection()) {
            throw new RuntimeException("无法连接到SSH服务器: " + HOST + ":" + PORT);
        }

        Session session = null;
        ChannelExec channel = null;

        try {
            JSch jsch = new JSch();
            session = jsch.getSession(USERNAME, HOST, PORT);
            session.setPassword(PASSWORD);

            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);

            session.connect(30000);

            // 使用清理后的IP构建命令
            String command = String.format(
                    "sudo grep -a \"\\\"ip\\\": \\\"%s\\\"\" /var/log/syslog 2>/dev/null | tail -n 50 || echo \"No results found\"",
                    cleanedIp
            );
            
            System.out.println("执行命令: " + command);
            
            channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand(command);
            
            InputStream in = channel.getInputStream();
            InputStream err = channel.getErrStream();
            
            channel.connect(10000); // 10秒超时
            
            // 读取输出
            StringBuilder output = new StringBuilder();
            byte[] buffer = new byte[1024];
            
            long startTime = System.currentTimeMillis();
            while (!channel.isClosed()) {
                // 读取标准输出
                while (in.available() > 0) {
                    int len = in.read(buffer, 0, 1024);
                    if (len > 0) {
                        output.append(new String(buffer, 0, len));
                    }
                }
                
                // 读取错误输出
                while (err.available() > 0) {
                    int len = err.read(buffer, 0, 1024);
                    if (len > 0) {
                        System.err.println("错误输出: " + new String(buffer, 0, len));
                    }
                }
                
                // 超时检查（30秒）
                if (System.currentTimeMillis() - startTime > 30000) {
                    throw new RuntimeException("命令执行超时");
                }
                
                Thread.sleep(500);
            }
            
            // 命令执行完成后读取剩余输出
            while (in.available() > 0) {
                int len = in.read(buffer, 0, 1024);
                if (len > 0) {
                    output.append(new String(buffer, 0, len));
                }
            }
            
            String result = output.toString().trim();
            System.out.println("命令结果: " + result);
            
            return result.isEmpty() ? "No matching entries found for IP: " + ip : result;
            
        } catch (JSchException e) {
            throw new RuntimeException("SSH连接错误: " + e.getMessage(), e);
        } catch (Exception e) {
            throw new RuntimeException("命令执行错误: " + e.getMessage(), e);
        } finally {
            if (channel != null) channel.disconnect();
            if (session != null) session.disconnect();
        }
    }
}